<?php


namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\brand\Brand as cBrand;
use Biz\service\brand\BrandCollegeService;
use Doraemon\service\Photos;
use Doraemon\service\Videos\Videos;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Photos as mPhoto;

class BrandCollegeController extends Controller
{

    public function __construct()
    {
        parent::__construct();
        Admin::script($this->setScript());
    }


    /**
     * @desc 品牌商学院NOTE列表
     *
     * @param  Request  $request
     * @param  Content  $content
     *
     * @return Content
     */
    public function noteList(Request $request, Content $content)
    {
        $infos = BrandCollegeService::getList();
        if ($infos) {
            $objIdList = array_unique(array_column($infos, 'obj_id'));
            $notes = Photos::getPhotos($objIdList, true);
            $video_ids = array_filter(array_unique(array_column($notes,
                'video_id')));
            $videos = Videos::getCanUseVideoInfosByIds($video_ids);
            foreach ($infos as $key => $value) {
                $infos[$key]['index'] = $key + 1;
                $infos[$key]['title'] = $notes[$value['obj_id']]['title']
                    ?: '';
                $infos[$key]['pic_id'] = $notes[$value['obj_id']]['pic_id']
                    ?: null;
                $infos[$key]['thumb_pic_url']
                    = $notes[$value['obj_id']]['thumb_pic_url'] ?: null;
                $infos[$key]['video_id'] = $notes[$value['obj_id']]['video_id']
                    ?: null;

                $infos[$key]['status'] = isset($notes[$value['obj_id']],$notes[$value['obj_id']]['status'])
                        ? $notes[$value['obj_id']]['status'] : mPhoto::STATUS_DELETE;

                $infos[$key]['show_type']
                    = BrandCollegeService::showType($notes[$value['obj_id']]['show_type']);
                $infos[$key]['publish_time']
                    = $notes[$value['obj_id']]['addtime']
                    ?: null;
                if (Photos::SHOW_TYPE_VIDEO
                    == $notes[$value['obj_id']]['show_type']
                ) {
                    $infos[$key]['thumb_pic_url']
                        = $videos[$notes[$value['obj_id']]['video_id']]['thumb_pic_url'];
                }
                $infos[$key]['preview_url']
                    = Hhzurl::h5PhotoShow($value['obj_id']);
            }
        }
        $gridModel = new pGridDataModel($infos);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {
                    $create->text('obj_id', 'obj_id');
                });
                $grid->column("id", 'ID')->sort();
                $grid->column("obj_id", 'obj_id')->display(function ($obj_id) {
                    return "<span style='color:#3c8dbc;' onclick='javascript:layer.open({                                
                                type: 2,
                                title: \"预览\",
                                maxmin: true,
                                area: [\"300px\", \"533px\"],
                                content: \"".$this->preview_url."\"
                                });'>$obj_id</span>";
                });
                $grid->column("title", '标题')->width(250);
                $grid->column("status", '状态')->display(function () {
                    return BrandCollegeService::getStatus($this->status);
                });
                $grid->column("show_type", '类型');
                $grid->column("publish_time", '发布时间')->display(function (
                    $publishtime
                ) {
                    return $publishtime > 0 ? date("Y-m-d H:i:s", $publishtime) : '';
                })->width(180);
                $grid->column('thumb_pic_url', '预览图')->display(function (
                    $thumb_pic_url
                ) {
                    return "<img src='".$thumb_pic_url."' width=150 />";
                })->width(250);
                $grid->column("operator_id", '操作者')->display(function ($operator
                ) {
                    return Admin::user()->find($operator)->name;
                })->width(120);
                $grid->actions(function ($action) {
                    $action->disableEdit();
                });
            });
        $tab = new Tab();
        $tab->add('品牌商学院', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('品牌商学院')
            ->description(' ')
            ->breadcrumb(['text' => '品牌商学院']);
    }

    /**
     * @品牌商学院NOTE提交
     *
     * @param  Request  $request
     * @param  int      $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function noteSubmit(Request $request, $id = 0)
    {
        try {
            $params = $request->all();
            unset($params['_token']);
            $checkResult = BrandCollegeService::objIdCheck($params['obj_id']);
            if (!$checkResult) {
                throw new \Exception('无法找到此ID');
            }
            //redis缓存防止短时间内多次提交
            $lockKey = 'brand:college:'.$params['obj_id'];
            if(cBrand::isLock($lockKey,30)){
                throw new \Exception('操作过于频繁，请稍后再试');
            }
            $objCount = BrandCollegeService::objCount();
            if ($objCount >= BrandCollegeService::MAX_SET_NOTE_COUNT) {
                throw new \Exception('列表已满');
            }
            if (BrandCollegeService::objExsit($params['obj_id'])) {
                throw new \Exception('obj已存在');
            }
            $result = BrandCollegeService::insterObj($params['obj_id']);
            if ($result) {
                return response()->json([
                    'status'  => true,
                    'message' => '操作成功'
                ]);
            }
            return response()->json([
                'status'     => false,
                'validation' => false,
                'message'    => '操作失败'
            ]);
        } catch (\Exception $exception) {
            Log::debug($exception->getMessage());
            return response()->json([
                'status'     => false,
                'validation' => false,
                'message'    => $exception->getMessage(),
            ]);
        }
    }

    /**
     * @desc 品牌商学院NOTE删除
     *
     * @param  Request  $request
     * @param           $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function noteDelete(Request $request, $id)
    {
        try {
            $result = BrandCollegeService::deleteObj($id);
            if ($result) {
                return response()->json([
                    'status'  => true,
                    'message' => '操作成功'
                ]);
            }

            return response()->json([
                'status'  => false,
                'message' => '操作失败'
            ]);
        } catch (\Exception $exception) {
            Log::debug($exception->getMessage(), []);
            return response()->json([
                'status'  => false,
                'message' => "操作失败",
            ]);
        }
    }

    /**
     * @desc 品牌商学院NOTE排序
     *
     * @param  Request  $request
     * @param  Content  $content
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function noteSort(Request $request)
    {
        $sort = $request->input('sort');
        if (isset($sort)) {
            BrandCollegeService::sortObj($sort);
        }
    }

    /**
     * @desc 品牌商学院Note数量
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNoteCount()
    {
        $count = BrandCollegeService::objCount();
        return response()->json([
            'count' => $count,
        ]);
    }

    /**
     * @desc 重写JS删除事件
     * @return string
     */
    public static function setScript()
    {
        return <<<SCRIPT
        $(document).ready(function(){
            $('.grid-row-delete').unbind('click').click(function() {
                var objCount = 0;
                $.ajax({
                    method: 'get',
                    url: '/admin/brand/college/notes/count',
                    cache:false,
                    async:false, 
                    success: function (data) {
                        if(data){
                            objCount = data.count;
                        }
                    }
                });
                var id = $(this).data('id');
                var confirm_msg = "确认删除?";
                if(objCount == 3){
                    confirm_msg = '删除后客户端将隐藏“品牌商学院”模块，是否确认删除？';
                }
                swal({
                    title: confirm_msg,
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                        return new Promise(function(resolve) {
                            $.ajax({
                                method: 'post',
                                url: '/admin/brand/college/notes/' + id,
                                data: {
                                    _method:'delete',
                                    _token:LA.token,
                                },
                                success: function (data) {
                                    $.pjax.reload('#pjax-container');
                                    resolve(data);
                                }
                            });
                        });
                    }
                }).then(function(result) {
                    var data = result.value;
                    if (typeof data === 'object') {
                        if (data.status) {
                            swal(data.message, '', 'success');
                        } else {
                            swal(data.message, '', 'error');
                        }
                    }
                });
            });
        });
SCRIPT;
    }

}